<script setup lang="tsx">
import { PropType, ref } from 'vue'
import { CurdData, FieldEnum, SchemaConfig } from '@/api/invoice/types'
import { getEnumApi } from '@/api/invoice'
import { getSelectListApi as getOperatorSelectListApi } from '@/api/operator'
import { SelectOption } from '@/api/global/types'
import { useI18n } from '@/hooks/web/useI18n'
import { useEnumeratePicker, useEnumerateMultiplePicker } from '@/utils'
const { t } = useI18n()

// 使用 ref 声明响应式变量 isExpanded
const isExpanded = ref(true)

// 切换展开/收起状态的方法
const togglePanel = () => {
  isExpanded.value = !isExpanded.value
}

const props = defineProps({
  currentRow: {
    type: Object as PropType<Nullable<CurdData>>,
    default: () => null
  }
})
const { query } = useRoute()

const isLoading = ref(true) // 设置加载状态
let operatorOptions: SelectOption[] = []
let customerOption: SelectOption[] = []
let orderOption: SelectOption[] = []
let paymentOption: SelectOption[] = []

const state = reactive({
  paymentArr: [] as string[],
  invoiceTypeOption: [] as SelectOption[]
})
type imageType = {
  id: number
  url: string
  name: string
}
let attachList = ref<imageType[]>([])
let invoiceAttachList = ref<imageType[]>([])
const dialogVisible = ref(false)
const previewImage = ref('')
const previewPDF = ref('')

const previewVisible = ref(false)
const previewTitle = ref('')
const previewType = ref('')
const dialogFile = ref<imageType>({
  id: 0,
  url: '',
  name: ''
})
const fileExtensions = {
  image: ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.svg'],
  pdf: ['.pdf'],
  text: ['.txt', '.html', '.md']
}
// 判断文件是否可以预览
const isPreviewable = (fileUrl: string) => {
  const extension = fileUrl.slice(fileUrl.lastIndexOf('.')).toLowerCase()

  if (fileExtensions.image.includes(extension)) {
    return 'image'
  }
  if (fileExtensions.pdf.includes(extension)) {
    return 'pdf'
  }
  if (fileExtensions.text.includes(extension)) {
    return 'text'
  }
  return 'other' // 无法预览的文件类型
}

// 文件点击事件处理
const handleFileClick = (fileParams) => {
  const type = isPreviewable(fileParams.url)
  console.log(type)
  if (type === 'other') {
    // 如果文件不可预览，直接下载
    handleFileDownload(fileParams)
  } else {
    // 如果文件可预览，弹出预览框
    previewType.value = type
    previewTitle.value = fileParams.name
    previewVisible.value = true
    dialogFile.value.url = fileParams.url
  }
}

const handleFileDownload = async (fileParams) => {
  try {
    // 如果是图片文件，打开新标签页
    if (fileParams.url && fileParams.url.match(/\.(jpg|jpeg|png|gif|bmp)$/i)) {
      // 在新标签页中打开图片
      window.open(fileParams.url, '_blank')
    } else {
      // 对于其他文件类型，直接使用文件 URL进行下载
      const link = document.createElement('a')
      link.download = fileParams.name || 'download' // 设置文件名
      link.href = fileParams.url
      link.target = '_blank'
      link.click()
    }
  } catch (error) {
    console.error('Error handling file download or open:', error)
  }
}

// 关闭预览窗口
const handleClosePreview = () => {
  previewVisible.value = false
  previewType.value = '' // 重置文件类型
}

const handleClose = () => {
  dialogVisible.value = false
}

const fetchData = async () => {
  await getEnumApi({ field: 'all' }).then((res) => {
    state.invoiceTypeOption = res.data.invoice_type
    useEnumeratePicker(state.invoiceTypeOption, 2)
  })
  await getOperatorSelectListApi({}).then((res) => {
    operatorOptions = res.data.list
  })
  state.paymentArr = props.currentRow?.payment_ids ? props.currentRow.payment_ids.split(',') : []

  customerOption = props.currentRow?.customer_option || []
  orderOption = props.currentRow?.order_option || []
  paymentOption = props.currentRow?.payment_option || []
  attachList.value = props.currentRow?.attach_list || []
  invoiceAttachList.value = props.currentRow?.invoice_attach_list || []
  isLoading.value = false // 数据加载完成后更新状态
}

fetchData()

// 预览图片
const handlePicturePreview = (url: string) => {
  // previewImageList.value = attachList.value.map((item) => item.url) // 生成所有图片的 URL 数组
  // previewIndex.value = previewImageList.value.indexOf(url) // 找到当前图片的索引
  // showViewer.value = true // 显示预览组件
}
</script>

<template>
  <el-card shadow="always">
    <div @click="togglePanel" class="header cursor-pointer">
      <span>基本信息</span>
      <el-icon v-if="isExpanded">
        <el-icon-arrow-down />
      </el-icon>
      <el-icon v-else>
        <el-icon-arrow-right />
      </el-icon>
    </div>
    <el-collapse-transition>
      <div v-show="isExpanded" v-if="!isLoading" class="w-full flex justify-between">
        <div class="w-100%">
          <el-descriptions
            title="基础信息"
            border
            :column="1"
            label-align="left"
            content-align="left"
          >
            <el-descriptions-item :span="24" :label="t('invoice.invoice_no')">
              {{ currentRow?.invoice_no }}
            </el-descriptions-item>
            <el-descriptions-item :span="24" :label="t('invoice.applicant')">
              {{ useEnumeratePicker(operatorOptions, currentRow?.applicant ?? '') }}
            </el-descriptions-item>

            <el-descriptions-item :span="24" :label="t('invoice.customer_id')">
              <ElLink type="primary" href="javascript:void(0)">
                {{ useEnumeratePicker(customerOption, currentRow?.customer_id ?? '') }}
              </ElLink>
            </el-descriptions-item>
            <el-descriptions-item :span="24" :label="t('invoice.order_id')">
              <ElLink type="primary" href="javascript:void(0)">
                {{ useEnumerateMultiplePicker(orderOption, String(currentRow?.order_id) ?? '') }}
              </ElLink>
            </el-descriptions-item>
            <el-descriptions-item :span="24" :label="t('invoice.invoicing_date')">
              {{ currentRow?.invoicing_date }}
            </el-descriptions-item>
            <el-descriptions-item :span="24" :label="t('invoice.tax_refund')">
              <span v-if="currentRow?.tax_refund === 1">是</span>
              <span v-else>否</span>
            </el-descriptions-item>
            <el-descriptions-item :span="24" :label="t('invoice.taxrefund_amount')">
              {{ currentRow?.taxrefund_amount }}
            </el-descriptions-item>
            <el-descriptions-item :span="24" :label="t('invoice.invoice_amount')">
              {{ currentRow?.invoice_amount }}
            </el-descriptions-item>
            <el-descriptions-item :span="24" :label="t('invoice.payment_ids')">
              <ElLink
                type="primary"
                href="javascript:void(0)"
                v-for="item in state.paymentArr"
                :key="item"
              >
                {{ useEnumeratePicker(paymentOption, Number(item) ?? '') }} &nbsp;&nbsp;
              </ElLink>
            </el-descriptions-item>
          </el-descriptions>
          <el-divider border-style="dashed" />
          <el-descriptions
            title="扩展信息"
            border
            :column="1"
            label-align="left"
            content-align="left"
          >
            <el-descriptions-item :span="24" :label="t('invoice.invoice_type')">
              {{ useEnumeratePicker(state.invoiceTypeOption, 2) }}
            </el-descriptions-item>
            <el-descriptions-item :span="24" :label="t('invoice.remark')">
              {{ currentRow?.remark }}
            </el-descriptions-item>
            <el-descriptions-item :span="24" :label="t('invoice.attach')">
              <div>
                <div class="box-card" v-for="(file, index) in attachList" :key="index">
                  <div class="clearfix">
                    <span>{{ file.name }}</span
                    >&nbsp;&nbsp;&nbsp;&nbsp;
                    <el-button @click="handleFileClick(file)" type="text">预览</el-button>
                    <el-button @click="handleFileDownload(file)" type="text">下载</el-button>
                  </div>
                </div>

                <!-- 显示图片预览 -->
                <!-- <el-dialog v-model="dialogVisible" :before-close="handleClose">
                  <img width="100%" :src="previewImage" alt="文件预览" />
                </el-dialog> -->
                <!-- 使用Element Plus的Dialog组件来显示预览 -->
                <el-dialog
                  v-model="previewVisible"
                  :title="previewTitle"
                  width="80%"
                  height="92%"
                  :before-close="handleClosePreview"
                >
                  <!-- 根据文件类型显示预览内容 -->
                  <div v-if="previewType === 'image'">
                    <img :src="dialogFile?.url" alt="预览图片" class="w-80% ml-10%" />
                  </div>
                  <div v-if="previewType === 'pdf'">
                    <iframe
                      :src="dialogFile?.url"
                      style="width: 100%; height: 80vh"
                      frameborder="0"
                    ></iframe>
                  </div>
                  <div v-if="previewType === 'text'">
                    <iframe
                      :src="dialogFile?.url"
                      style="width: 100%; height: 80vh"
                      frameborder="0"
                    ></iframe>
                  </div>
                  <div v-if="previewType === 'other'">
                    <p>无法预览此文件，您可以下载它。</p>
                  </div>
                </el-dialog>
              </div>
            </el-descriptions-item>
            <el-descriptions-item :span="24" :label="t('invoice.invoice_attach')">
              <div>
                <div class="box-card" v-for="(file, index) in invoiceAttachList" :key="index">
                  <div class="clearfix">
                    <span>{{ file.name }}</span
                    >&nbsp;&nbsp;&nbsp;&nbsp;
                    <el-button @click="handleFileClick(file)" type="text">预览</el-button>
                    <el-button @click="handleFileDownload(file)" type="text">下载</el-button>
                  </div>
                </div>

                <!-- 显示图片预览 -->
                <el-dialog v-model="dialogVisible" :before-close="handleClose">
                  <img width="100%" :src="previewImage" alt="文件预览" />
                </el-dialog>
              </div>
            </el-descriptions-item>

            <el-descriptions-item :span="24" :label="t('invoice.remark')">
              {{ currentRow?.remark }}
            </el-descriptions-item>
          </el-descriptions>
          <el-divider border-style="dashed" />
          <el-descriptions
            title="系统信息"
            border
            :column="1"
            label-align="left"
            content-align="left"
          >
            <el-descriptions-item :span="24" :label="t('invoice.creator')">
              {{ useEnumeratePicker(operatorOptions, currentRow?.creator ?? '') }}
            </el-descriptions-item>
            <el-descriptions-item :span="24" :label="t('invoice.create_time')">
              {{ currentRow?.create_time }}
            </el-descriptions-item>
            <el-descriptions-item :span="24" :label="t('invoice.update_time')">
              {{ currentRow?.update_time }}
            </el-descriptions-item>
          </el-descriptions>
        </div>
      </div>
    </el-collapse-transition>
  </el-card>
</template>

<style scoped>
.header {
  display: flex;
  height: 40px;
  padding: 0 10px;
  margin-bottom: 10px;
  font-weight: 900;
  background-color: #f3f3f3;
  border-radius: 5px;
  align-items: center;
  justify-content: space-between;
}

:deep(.is-bordered-label) {
  width: 200px;
}

/* 隐藏上传按钮 */

/* 隐藏 el-upload 的文本模式按钮 */
.only-preview :deep(.el-upload--picture-card) {
  display: none !important;
}

/* 也隐藏 el-upload--picture-card 的上传按钮 */
.only-preview :deep(.el-upload--picture-card) {
  display: none !important;
}
</style>
